<?php

namespace App\Service;

use Anam\PhantomMagick\Converter;
use Anam\PhantomMagick\Str;
use App\Models\ShareProduct;
use Flaravel\Upload\Fupload;

class ShareService extends Converter
{

    /**
     * 生成小程序分享图片
     *
     * @param string $url  商品详情html
     * @param bool $compress 是否压缩图片
     * @return string 图片路径
     */
    public function generateShareImage($url)
    {
        if (!$url) {
            return false;
        }
        $file = storage_path('app/public/share'). '/' .md5(uniqid()) . '.png';
        $this->setBinary('/usr/local/bin/phantomjs');
        $this->source($url)->toPng([
            'dimension' => '575px',
            'zoomfactor' => 1.5,   //放大倍数
            'quality' => 90,       // 质量
        ])->save($file);
        self::compress($file);
        return Fupload::upload(file_get_contents($file),'share', 'png');
    }

    // 去除一个liunx下的bug
    public function verifyBinary($binary)
    {
        $uname = strtolower(php_uname());

        if (Str::contains($uname, 'darwin')) {
            if (! shell_exec(escapeshellcmd("command -v {$binary} >/dev/null 2>&1"))) {
                return false;
            }
        } elseif (Str::contains($uname, 'win')) {
            if (! shell_exec(escapeshellcmd("{$binary}"))) {
                return false;
            }
        } elseif (Str::contains($uname, 'linux')) {
            if (! shell_exec(escapeshellcmd("{$binary}"))) {
                return false;
            }
        } else {
            throw new \RuntimeException("Unknown operating system.");
        }
        return true;
    }

    /**
     * 压缩图片.
     *
     * @param $file
     */
    public static function compress($file)
    {
        list($width, $height, $type) = getimagesize($file);
        $new_width  = $width * 1;
        $new_height = $height * 1;

        $resource = imagecreatetruecolor($new_width, $new_height);
        $image    = imagecreatefrompng($file);
        imagecopyresampled($resource, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        imagepng($resource, $file, 9);
        imagedestroy($resource);
    }
}
